const Joi = require('joi');

function getMessage(status) {
    status = parseInt(status / 100);
    switch (status) {
        case 2:
            return '请求成功！';
        case 3:
            return '请求重定向';
        case 4:
            return '请求错误！';
        default:
            return '请求失败！';
    }
}

// 添加统一的返回结果方法
module.exports = function (req, res, next) {
    res.sendResult = function (data, status, message) {
        var fmt = req.query.fmt ? req.query.fmt : "rest";
        if (fmt == "rest") {
            res.json({
                data,
                "meta": {
                    "msg": message || getMessage(status),
                    status
                }
            });
        }
    };
    res.isFakeID = _id => {
        const schema = {
            _id: Joi.string().required().regex(/^[0-9a-fA-F]{24}$/).error(new Error('非法id'))
        }
        // 验证
        const {
            error
        } = Joi.validate({
            _id
        }, schema, {
            // 检测到所有错误
            abortEarly: false
        });
        if (error) {
            res.sendResult(null, 400, error.message);
            return true;
        }
    }
    next();
}